import {Component, EventEmitter, Input, OnChanges, OnInit, Output} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {NavigationExtras, Router} from "@angular/router";

@Component({
  selector: 'app-choosecount',
  templateUrl: './choosecount.component.html',
  styleUrls: ['./choosecount.component.scss']
})
export class ChoosecountComponent implements OnInit, OnChanges {
   public show: any = 0;
   public num: any = 1;
   public successAddShopcar: any = false;
   @Input() msg: any;
  @Input() msg1: any;
   @Output() private outer = new EventEmitter < string >();
  constructor( private http: HttpClient, private router: Router) {
  }
  ngOnChanges() {
     this.show = this.msg;
  }
  ngOnInit() {

  }
  doReduce() {
    if ( this.num === 1) {
      this.num = 1;
    } else {
      this.num = this.num - 1;
    }
  }
  doAdd() {
    if ( this.num <= 99) {
     this.num = this.num + 1;
    } else {
      this.num = this.num + 1;
    }
  }
  cancel() {
    this.show = 0;
  }
  doOk() {
    const params = {
      user_id: localStorage.user,
      goods_id: this.msg1,
      goods_count: this.num
    };
    const heads = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    if ( this.show % 2 !== 0) {
      // 点击的是加入购物车
      this.successAddShopcar = true;
      // 窗口隐藏
      this.show = 0;
      this.outer.emit( [this.num, this.successAddShopcar].toString());
      // 添加到服务器
      const url = 'http://192.168.2.228:8080/shoppingcart/add';
      this.http.post(url, params, heads).subscribe( res => {
        console.log("添加成功");
      });
    } else {
      const navigationExtras: NavigationExtras = {
        queryParams: {
            goods_id: this.msg1,
            goods_count: this.num
        }
      };
      // 跳往生成订单页面
      this.router.navigate(['/paydetail'], navigationExtras);
    }
    }
}
